package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.UserService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.List;

/**
 * 主页面动态显示用户名
 */
@RestController
@RequestMapping("/user")
public class UserController {
    //获取当前登录用户的用户名

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Reference
    private UserService userService;
    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/getUsername")
    public Result getUsername() {
        try {
            System.out.println("1111111111111111111111111111111111111111");
            //通过框架提供的上下文对象获取框架的user对象
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            //通过框架的user对象获取用户名
            String username = user.getUsername();
            //成功返回
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            //失败返回
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.findPage(queryPageBean);
    }
    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){
        try{
            String s = DateUtils.parseDate2String(user.getBirthday(),"yyyy-MM-dd");
            int a= Integer.parseInt(s.substring(8, 10));
            String s1 = DateUtils.parseDate2String(new Date(),"yyyy-MM-dd");
            int b = Integer.parseInt(s1.substring(8, 10));
            if (a>b){
                return new Result(false,MessageConstant.ADD_USER_fail);
            }
            String encode = passwordEncoder.encode(user.getPassword());
            user.setPassword(encode);
            userService.add(user,roleIds);
            return new Result(true,MessageConstant.ADD_USER_SUCCESS);
        }catch (Exception e){
            return  new Result(false,MessageConstant.ADD_USER_FILE);
        }
    }
    //通过用户Id查询
    @RequestMapping("/findById")
    public Result findById(Integer userId){
        try {
            com.itheima.pojo.User user = userService.findById(userId);
            return  new Result(true,MessageConstant.QUERY_USER_SUCCESS,user);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_USER_FAIL);
        }
    }
    //根据用户id查询所有角色id
    @RequestMapping("/findroleIdsByuserId")
    public Result findroleIdsByuserId(Integer userId){
        try{
            List<Integer> list= userService.findroleIdsByuserId(userId);
            return  new Result(true,MessageConstant.QUERY_ROLE_SUCCESS,list);
        }catch (Exception e){
            return new Result(false,MessageConstant.QUERY_ROLE_FAIL);
        }
    }
    //编辑用户信息
    @RequestMapping("/edit")
    public Result edit(@RequestBody com.itheima.pojo.User user, Integer[] roleIds){
        try{
            String encode = passwordEncoder.encode(user.getPassword());
            user.setPassword(encode);
            userService.edit(user,roleIds);
            return new Result(true,MessageConstant.EDIT_USER_SUCCESS);
        }catch (Exception e){
            return new Result(false,MessageConstant.EDIT_USER_FAIL);
        }
    }
    //删除用户
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try{
            userService.delete(id);
            return new Result(true,MessageConstant.DELETE_USER_SUCCESS);
        }catch (Exception e){
            return  new Result(false,MessageConstant.DELETE_USER_FILE);
        }
    }

    @RequestMapping("/password")
    public Result editPassword(@RequestBody com.itheima.pojo.User user, String validateCode) {
        //从页面获取手机号
        String telephone = user.getTelephone();
        //从redis中获取验证码
        Jedis resource = jedisPool.getResource();
        String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        //归还资源
        resource.close();
        //判断发送的验证码和输入的验证码是否相同
        if (validateCodeInRedis != null && validateCode != null && validateCodeInRedis.equals(validateCode)) {
            //如果对比相同，设置预约类型，分为微信预约、电话预约
            try {
                userService.editPassword(user, validateCode);
                return new Result(true, MessageConstant.EDIT_PASSWORD_SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, MessageConstant.EDIT_PASSWORD_FAIL);
            }
        }
        return new Result(false,MessageConstant.VALIDATECODE_ERROR);

    }
}
